package root.service;

import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.jfinal.plugin.activerecord.Record;
import com.jfinal.plugin.activerecord.SqlPara;
import root.utils.StringHelper;

import java.util.Date;
import java.util.List;

/**
 * @author 吕梁山
 * @date 2019-01-19
 */
public class ArticleService {

    public Page<Record> getArticlePage(String article_title, String article_type, String status, int pageNumber, int pageSize){
        String sql = "select a.*,t.type_name";
        sql += ",(select count(0) from t_article_comment t where t.article_id = a.id) article_comment_nums ";
        sql += " from t_article a, t_article_type t where t.id = a.article_type";
        if(StringHelper.isNotEmpty(article_title)){
            sql += " and a.article_title like '%" + article_title + "%'";
        }
        if(StringHelper.isNotEmpty(article_type)){
            sql += " and a.article_type = " + article_type;
        }
        if(StringHelper.isNotEmpty(status)){
            sql += " and a.status = " + status;
        }
        sql += " order by a.create_date desc";
        return Db.paginate(pageNumber, pageSize, new SqlPara().setSql(sql));

    }

    public Record getArticle(String articleId) {
        String sql = "select * from t_article where id = " + articleId;
        return Db.findFirst(sql);
    }

    public boolean saveArticle(Record article) {
        if(StringHelper.isNotEmpty(article.getStr("id"))){
            return Db.update("t_article", article);
        } else {
            article.set("create_date", new Date());
            return Db.save("t_article", article);
        }
    }

    public Page<Record> getArticleTypePage(int pageNumber, int pageSize) {
        String sql = "select t.*,(select count(0) from t_article a where a.article_type = t.id) article_num from t_article_type t";
        return Db.paginate(pageNumber, pageSize, new SqlPara().setSql(sql));
    }

    public Record getArticleType(String id) {
        String sql = "select * from t_article_type where id = " + id;
        return Db.findFirst(sql);
    }

    public boolean saveArticleType(Record articleType) {
        if(StringHelper.isNotEmpty(articleType.getStr("id"))){
            return Db.update("t_article_type", articleType);
        } else {
            articleType.set("create_date", new Date());
            return Db.save("t_article_type", articleType);
        }
    }

    public List<Record> getAllArticleType() {
        String sql = "select * from t_article_type where status = 0 order by create_date desc ";
        return Db.find(sql);
    }
}
